
import * as Fiber from 'fiber';
let page_types = {
  // 待发 已发
  draft: 'draft',
  sent: 'sent',
  pending: 'pending',
  finish: 'finish'
};

// 归档
let lockProcessIds = [];
function doPigeonhole(selectedRows, callback, pageType = 'pending') {
  const rows = selectedRows;
  if (rows.length === 0) {
    Fiber.message.warning($.i18n('collaboration.pighole.alert.select'));
    return;
  }

  console.log("$.ctp.trigger", "beforeDoPigeonhole", rows);
  const sendDevelop = $.ctp.trigger('beforeDoPigeonhole', rows);
  if (!sendDevelop) {
    return;
  }

  let secretBatchCheckParams = new Array();
  let ids = new Array();
  let check = false;
  let archiveSubject = '';
  let workflowSubject = '';
  let superNodeSubject = '';
  let opinionSubject = '';
  let processIndex = 0;
  let canContinueExecute = true;
  for (let i = 0; i < rows.length; ++i) {
    const elem = rows[i];
    let param = new batchParam(elem.processId, elem.affairId, elem.summaryId, elem.subject);
    secretBatchCheckParams.push(param);
    let isSuperNode = elem.superNode;
    if (isSuperNode === true) {
      check = true;
      superNodeSubject += '<br>' + '&lt;' + escapeStringToHTML(elem.subject) + '&gt;';
    } else if (pageType == 'pending') {
      // 待办的逻辑(还需要翟峰多查询几个条件)
      if (elem.templeteId) {
        // 未办理的模板协同不允许直接归档或删除
        check = true;
        archiveSubject += '<br>' + '&lt;' + escapeStringToHTML(elem.subject) + '&gt;';
      }

      // 添加提交锁
      let lockWorkflowRe = lockWorkflow(elem.processId, window._currentUser.id, 14);
      if (lockWorkflowRe[0] == 'false') {
        check = true;
        if (workflowSubject != '') {
          workflowSubject += '<br>';
        }
        workflowSubject +=
          lockWorkflowRe[1] + '<br>' + '&lt;' + escapeStringToHTML(elem.subject) + '&gt;';
      } else {
        lockProcessIds[processIndex++] = elem.processId;
      }

      if (elem.canDeleteORarchive) {
        // 以下事项要求意见不能为空，不能直接归档或删除
        check = true;
        opinionSubject += '<br>' + '&lt;' + escapeStringToHTML(elem.subject) + '&gt;';
      }
      // 指定回退时不能处理
      let canSubmitWorkFlowRe = canSubmitWorkFlow(elem.workitemId);
      if (canSubmitWorkFlowRe[0] == 'false') {
        $.alert({
          msg: canSubmitWorkFlowRe[1],
          ok_fn: function () {
            // 做兼容处理
            if (parent && parent.document.getElementById('mainIframe')) {
              parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
            } else {
              window.location.reload(true);
            }
          }
        });
        check = true;
        unlockWorkflow();
        canContinueExecute = false;
        break;
      }
      if (!isAffairValid(elem.affairId)) {
        check = true;
        unlockWorkflow();
        canContinueExecute = false;
        break;
      }
    }
  }

  if (!canContinueExecute) {
    callback && callback({ success: false, result: {} });
    return;
  }
  if (archiveSubject.length > 1) {
    $.alert({
      msg: $.i18n('collaboration.template.notHandle.notDeleteArchive') + '<br>' + archiveSubject,
      ok_fn: function () {
        // 做兼容处理
        if (parent && parent.document.getElementById('mainIframe')) {
          parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
        } else {
          window.location.reload(true);
        }
      }
    });
    unlockWorkflow();
    return;
  }

  if (superNodeSubject.length > 1) {
    // 超级节点不允许转发
    $.alert({
      msg: $.i18n('workflow.supernode.msg.not_archive.js') + '<br>' + superNodeSubject,
      ok_fn: function () {
        // 做兼容处理
        if (parent && parent.document.getElementById('mainIframe')) {
          parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
        } else {
          window.location.reload(true);
        }
      }
    });
    unlockWorkflow();
    return;
  }

  if (workflowSubject.length > 1) {
    Fiber.message.warning(workflowSubject);
    unlockWorkflow();
    return;
  }
  if (opinionSubject.length > 1) {
    $.alert({
      msg: $.i18n('collaboration.template.notDeleteArchive.nullOpinion') + '<br>' + opinionSubject,
      ok_fn: function () {
        // 做兼容处理
        if (parent && parent.document.getElementById('mainIframe')) {
          parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
        } else {
          window.location.reload(true);
        }
      }
    });
    unlockWorkflow();
    return;
  }
  if (check) {
    unlockWorkflow();
    return;
  }

  let secretCheckResult = callBackendMethod(
    'secretAjaxManager',
    'batchCheckUserSecretLevel',
    secretBatchCheckParams
  );
  let secretCheck = new SecretCheck(secretCheckResult, 'pigeonhole');
  let affairIdArray = secretCheck.getSuccessAffairIds();
  if (affairIdArray.length === 0) {
    secretCheck.messageDialog(unlockWorkflow);
    return;
  }
  ids = affairIdArray;
  callBackendMethod('colManager', 'getPigeonholeRight', ids, {
    success: function (jsonObj) {
      if (jsonObj != '') {
        $.alert({
          msg: escapeStringToHTML(jsonObj),
          ok_fn: function () {
            // 做兼容处理
            if (parent && parent.document.getElementById('mainIframe')) {
              parent.document.getElementById('mainIframe').contentWindow.location.reload(true);
            } else {
              window.location.reload(true);
            }
          }
        });
        unlockWorkflow();
      } else {
        doPigeonholeCheck(ids, pageType, secretCheck, callback);
      }
    }
  });
}

function unlockWorkflow() {
  if (lockProcessIds.length > 0) {
    for (let i = 0; i < lockProcessIds.length; i++) {
      releaseWorkflowByAction(lockProcessIds[i], window._currentUser.id, 14);
    }

    lockProcessIds.length = 0;
  }
}

function SecretCheck(result, operate) {
  this.secretCheckResult = result;
  this.operate = operate;

  SecretCheck.prototype.getOperate = function () {
    return this.operate;
  };

  SecretCheck.prototype.getSuccessAffairIds = function () {
    let affairIdArray = new Array();
    for (let i = 0; i < this.secretCheckResult.length; i++) {
      if (this.secretCheckResult[i].resultCode === 0) {
        affairIdArray.push(this.secretCheckResult[i].affairId);
      }
    }
    return affairIdArray;
  };

  SecretCheck.prototype.messageDialog = function (callback) {
    let ur1 = _ctxPath + '/collaboration/batchController.do?method=secretBatch';
    let dialog1 = $.dialog({
      url: ur1,
      title: $.i18n('common.system.hint.label'), //系统提示
      width: 450,
      height: 310,
      targetWindow: getCtpTop(),
      isDrag: true,
      transParams: this,
      buttons: [
        {
          text: $.i18n('common.button.close.label'), //关闭
          handler: function () {
            dialog1.close();
            if (callback) {
              callback();
            }
          }
        }
      ],
      closeParam: {
        show: true,
        handler: function () {
          dialog1.close();
          if (callback) {
            callback();
          }
        }
      },
      minParam: {
        show: false
      },
      maxParam: {
        show: false
      }
    });
  };

  SecretCheck.prototype.size = function () {
    return this.secretCheckResult.length;
  };

  SecretCheck.prototype.getCancelData = function () {
    let result = new ArrayList();
    for (let i = 0; i < this.secretCheckResult.length; i++) {
      let ele = this.secretCheckResult[i];
      if (ele && ele.resultCode !== 0) {
        result.add(ele);
      }
    }
    return result;
  };
}

// ajax判断事项是否可用。
function isAffairValid(affairId) {
  let msg = callBackendMethod('portalAffairManager', 'checkAffairValid', affairId);
  if ($.trim(msg) != '') {
    Fiber.message.warning(msg);
    return false;
  }
  return true;
}

// 检查是否已存在归档协同
window.doPigeonholeCheckCallbackIds = '';
window.doPigeonholeCheckCallbackPageType = '';
window.doPigeonholeCallback = null;
window.doPigeonholeCheckSecretCallback = null;
function doPigeonholeCheck(ids, pageType, secretCheck, callback) {
  window.doPigeonholeCheckCallbackIds = ids;
  window.doPigeonholeCheckCallbackPageType = pageType;
  window.doPigeonholeCallback = callback;
  window.doPigeonholeCheckSecretCallback = secretCheck;

  let result = pigeonhole(null, null, null, null, null, 'doPigeonholeCheckCallback');
}

/**
 * doPigeonholeCheck归档回调
 */
window.doPigeonholeCheckCallback = function (result) {
  if (result) {
    if (result != 'cancel') {
      let folder = result.split(',');
      let callerResponder = new CallerResponder();
      callerResponder.success = function (jsonObj) {
        if (jsonObj === '' || confirm(jsonObj)) {
          doPigeonholeCol(
            doPigeonholeCheckCallbackIds,
            folder,
            doPigeonholeCheckCallbackPageType,
            doPigeonholeCheckSecretCallback,
            doPigeonholeCallback
          );
          unlockWorkflow();
        } else {
          unlockWorkflow();
        }
      };
      try {
        callBackendMethod(
          'colManager',
          'getIsSamePigeonhole',
          doPigeonholeCheckCallbackIds,
          folder[0],
          callerResponder
        );
      } catch (e) {
        unlockWorkflow();
      }
    } else {
      unlockWorkflow();
    }
  } else {
    unlockWorkflow();
  }
};

function doPigeonholeCol(ids, folder, pageType, secretCallback, doPigeonholeCallback) {
  for (let i = 0; i < ids.length; i++) {
    callBackendMethod('colManager', 'transPigeonhole', ids[i], folder[0], pageType);
  }
  if (secretCallback.getCancelData().size() !== 0) {
    secretCallback.messageDialog();
  } else {
    //归档成功
    $.infor($.i18n('collaboration.grid.alert.archiveSuccess'));
  }
  callBackendMethod('colManager', 'transPigeonholeDeleteStepBackDoc', ids, folder[0]);
  doPigeonholeCallback && doPigeonholeCallback({ success: true, result: {} });
  //归档后关闭子页面打开的协同
  for (let i = 0; i < ids.length; i++) {
    let affairId = ids[i];
    try {
      closeOpenMultyWindow(affairId);
    } catch (e) { }
  }
}

function deleteItems(selectedRows, callback, pageType = 'pending', fromMethod = 'listPending') {
  if (!pageType || !page_types[pageType]) {
    Fiber.message.warning('pageType is illegal:' + pageType);
    // $.alert('pageType is illegal:' + pageType);
    return true;
  }
  let rows = selectedRows;
  let affairIds = '';
  let deleteSubject = '';
  if (rows.length <= 0) {
    // 请选择要删除的协同。
    Fiber.message.warning($.i18n('collaboration.grid.selectDelete'));
    // $.alert($.i18n('collaboration.grid.selectDelete'));
    return true;
  }
  console.log("$.ctp.trigger", "beforeDeleteColl");
  let sendDevelop = $.ctp.trigger('beforeDeleteColl');
  if (!sendDevelop) {
    callback && callback({ success: false, result: {} });
    return;
  }
  let processIndex = 0;
  let secretBatchCheckParams = new Array();
  let obj;
  for (let i = 0; i < rows.length; i++) {
    obj = rows[i];
    let param = new batchParam(obj.processId, obj.affairId, obj.summaryId, obj.subject);
    secretBatchCheckParams.push(param);
    try {
      closeOpenMultyWindow(obj.affairId, false);
    } catch (e) { }
    // 指定回退状态状态不能删除
    if (pageType == 'draft') {
      if (obj.subState == '16') {
        Fiber.message.warning($.i18n('collaboration.alert.CantModifyBecauseOfAppointStepBack'));
        // $.alert($.i18n('collaboration.alert.CantModifyBecauseOfAppointStepBack'));
        obj.checked = false;
        return true;
      }
    }

    // 当前节点设置不允许删除:
    if (!obj.canReMove) {
      if (rows.length == 1) {
        // 当前节点权限不可进行删除操作！
        Fiber.message.warning($.i18n('collaboration.alert.CantReMoveOne'));
        // $.alert($.i18n('collaboration.alert.CantReMoveOne'));
        obj.checked = false;
        return true;
      } else {
        // 根据当前节点权限以下流程不可删除！
        deleteSubject += '<br>&lt;' + escapeStringToHTML(obj.subject) + '&gt;';
        continue;
      }
    }

    if (pageType == 'pending') {
      if (obj.templeteId) {
        // 未办理的模板协同不允许直接归档或删除!
        Fiber.message.warning(
          $.i18n('collaboration.template.notHandle.notDeleteArchive')
        );
        obj.checked = false;
        return true;
      }

      let lockWorkflowRe = lockWorkflow(obj.processId, window._currentUser.id, 14);
      if (lockWorkflowRe[0] == 'false') {
        Fiber.message.warning(lockWorkflowRe[1]);
        obj.checked = false;
        return true;
      } else {
        lockProcessIds[processIndex++] = obj.processId;
      }
      // 以下事项要求意见不能为空，不能直接归档或删除:
      if (obj.canDeleteORarchive) {
        Fiber.message.warning(
          $.i18n('collaboration.template.notDeleteArchive.nullOpinion')
        );
        obj.checked = false;
        unlockWorkflow();
        return true;
      }
      // 指定回退时不能处理
      let canSubmitWorkFlowRe = canSubmitWorkFlow(obj.workitemId);
      if (canSubmitWorkFlowRe[0] == 'false') {
        Fiber.message.warning(canSubmitWorkFlowRe[1]);
        check = true;
        unlockWorkflow();
        return false;
      }
    }
  }
  if (deleteSubject.length > 1) {
    Fiber.message.warning($.i18n('collaboration.alert.CantReMove') + deleteSubject);
    // $.alert($.i18n('collaboration.alert.CantReMove') + deleteSubject);
    obj.checked = false;
    return true;
  }

  let confirm = $.confirm({
    // 该操作不能恢复，是否进行删除操作
    msg: $.i18n('collaboration.confirmDelete'),
    ok_fn: function () {
      let affairIdArray = [];
      let secretCheck = null;
      if ('draft' !== pageType) {
        let secretCheckResult = callBackendMethod(
          'secretAjaxManager',
          'batchCheckUserSecretLevel',
          secretBatchCheckParams
        );
        secretCheck = new SecretCheck(secretCheckResult, 'delete');
        affairIdArray = secretCheck.getSuccessAffairIds();
        if (affairIdArray.length === 0) {
          secretCheck.messageDialog(unlockWorkflow);
          return;
        }
      } else {
        for (let i = 0; i < secretBatchCheckParams.length; i++) {
          affairIdArray.push(secretBatchCheckParams[i].affairId);
        }
      }
      affairIds = affairIdArray.join(',');
      let obj = new Object();
      obj.pageType = pageType;
      obj.affairIds = affairIds;
      obj.fromMethod = fromMethod;
      callBackendMethod('colManager', 'checkCanDelete', obj, {
        success: function (flag) {
          if ('success' == flag) {
            // 循环删除，隔离后台的事务，否则多个流程事务一起提交工作流部分的数据可能会出错
            let ids = affairIds.split(',');
            for (let i = 0; i < ids.length; i++) {
              //collManager.deleteAffair(pageType,ids[i]);
              callBackendMethod('colManager', 'deleteAffair', pageType, ids[i]);
            }
            //关闭已经删除了事项打开的子页面
            for (let i = 0; i < ids.length; i++) {
              try {
                closeOpenMultyWindow(ids[i], false);
              } catch (e) { }
            }
            let successFn = function successFn() {
              unlockWorkflow();
              let totalNum = grid.p.total - 1;
              $('#summary').attr(
                'src',
                'listDesc.do?method=listDesc&type=' + tableId + '&size=' + totalNum
              );
              $('#' + tableId).ajaxgridLoad(getSearchValueObj());
            };
            if (secretCheck && secretCheck.getCancelData().size() !== 0) {
              secretCheck.messageDialog(successFn);
              return;
            }
            // 成功删除，并刷新列表
            $.messageBox({
              title: $.i18n('common.system.hint.label'),
              type: 0,
              msg: $.i18n('common.delete.success.label'),
              imgType: 0,
              ok_fn: function () {
                unlockWorkflow();
                callback && callback({ success: true, result: {} });
              },
              close_fn: function () {
                unlockWorkflow();
                callback && callback({ success: true, result: {} });
              }
            });
          } else {
            Fiber.message.warning(flag);
            unlockWorkflow();
          }
        },
        error: function (request, settings, e) {
          Fiber.message.warning(e);
          unlockWorkflow();
        }
      });
    },
    cancel_fn: function () {
      unlockWorkflow();
    }
  });
}

function batchParam(processId, affairId, objectId, subject) {
  this.processId = processId;
  this.affairId = affairId;
  this.objectId = objectId;
  this.subject = subject;
}

/**
 * 明细日志 弹出对话框
 * showFlag  初始化时 显示的内容 1:显示处理明细 2:显示流程日志 3:显示催办(督办)日志
 */
function showDetailLogDialog(summaryId, processId, showFlag, isHistoryFlag, affairId) {
  let checkResult = callBackendMethod('secretAjaxManager', 'checkUserSecretLevel', summaryId);
  if (checkResult && checkResult.length > 0) {
    Fiber.message.warning(checkResult);
    return;
  }

  const triggerParams = {summaryId, processId, showFlag, isHistoryFlag, affairId};
  console.log("$.ctp.trigger", "beforeShowDetailLog", triggerParams);
  const sendDevelop = $.ctp.trigger('beforeShowDetailLog', triggerParams);
  if (!sendDevelop) {
    return;
  }

  let url =
    _ctxPath +
    '/detaillog/detaillog.do?method=showDetailLog&summaryId=' +
    summaryId +
    '&processId=' +
    processId +
    '&showFlag=' +
    showFlag +
    '&isHistoryFlag=' +
    isHistoryFlag;

  let dialog = $.dialog({
    url: url,
    width: 1040,
    height: 480,
    title: $.i18n('collaboration.sendGrid.findAllLog'), //查看明细日志
    targetWindow: getCtpTop(),
    buttons: [
      {
        text: $.i18n('common.button.close.label'),
        handler: function () {
          dialog.close();
        }
      }
    ]
  });
}

function doubleClick(url) {
  // var parmas = [$('#summary'), $('.slideDownBtn'), $('#listPending')];
  // 公文用协同代码。。。
  if (url.indexOf('edoc') == -1 && url.indexOf('govdoc') == -1) {
    url += '&showTab=true';
  }
  let id = window.getMultyWindowId('affairId', url);
  if (isOcipSummary(url, id)) {
    window.openCtpWindow({url, id});
  } else {
    collaborationApi.showSummayDialogByURL(url);
  }
}

function isOcipSummary(url, id) {
  if (window._hasPlugin("ocip") && url.includes("method=summary&") && url.includes("showTab=true") && url.includes('affairId')) {
    return callBackendMethod("ocipColManager", "checkIsExchangeAffair", id);
  } else {
    return false;
  }
}

function smartCodeCallBack(reval) {
  if (reval && reval.openFrom) {
    // 如果有数据，新开一个窗口，打开协同
    setTimeout(() => {
      colSum(reval.affairId, reval.openFrom, reval.summaryId, reval.subState);
    }, 100);
  } else {
    Fiber.message.warning($.i18n('collaboration.erweima.nodata.js'));
    // $.alert($.i18n('collaboration.erweima.nodata.js'));
  }
}

function colSum(affairId, openFrom, summaryId, subState) {
  if (openFrom == 'listWaitSend') {
    editCol(affairId, summaryId, subState);
  } else {
    let url =
      _ctxPath +
      '/collaboration/collaboration.do?method=summary&openFrom=' +
      openFrom +
      '&affairId=' +
      affairId;
    if (openFrom == 'listSent' || openFrom == 'listDone') {
      url += '&dumpData=' + window.dataType;
    }
    doubleClick(url, null);
  }
}

function editCol(affairId, summaryId, subState) {
  let url =
    _ctxPath +
    '/collaboration/collaboration.do?method=newColl&summaryId=' +
    summaryId +
    '&affairId=' +
    affairId +
    '&from=waitSend&subState=' +
    subState +
    '&showTab=true';
  const obj = {
    url: url,
    id: affairId
  };
  const a8Top = getA8Top();

  if (a8Top.isMultipleTabs) {
    a8Top.openCtpWindow(obj);
  } else {
    openCtpWindow(obj);
  }
}

export default {
  doPigeonhole: doPigeonhole,
  deleteItems: deleteItems,
  showDetailLogDialog: showDetailLogDialog,
  isAffairValid: isAffairValid,
  doubleClick: doubleClick,
  smartCodeCallBack: smartCodeCallBack
};
